package cn.iocoder.yudao.module.reading.dal.mysql.assignment;

import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.reading.dal.dataobject.assignment.AssignmentBookDO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 作业绘本关联 Mapper
 *
 * @author 芋道源码
 */
@Mapper
public interface AssignmentBookMapper extends BaseMapperX<AssignmentBookDO> {

    /**
     * 根据作业ID查询绘本列表
     *
     * @param assignmentId 作业ID
     * @return 绘本关联列表
     */
    default List<AssignmentBookDO> selectByAssignmentId(Long assignmentId) {
        return selectList(new LambdaQueryWrapperX<AssignmentBookDO>()
                .eq(AssignmentBookDO::getAssignmentId, assignmentId)
                .orderByAsc(AssignmentBookDO::getSortOrder)
                .orderByAsc(AssignmentBookDO::getId));
    }

    /**
     * 根据作业类型判断绘本完成状态
     *
     * @param bookId 绘本ID
     * @param assignmentId 作业ID
     * @param userId 用户ID
     * @return 是否完成
     */
    @Select("SELECT " +
            "CASE " +
            "  WHEN ca.requirement_type = 'audio' THEN " +
            "    CASE " +
            "      WHEN EXISTS (SELECT 1 FROM user_recordings ur WHERE ur.user_id = #{userId} AND ur.book_id = #{bookId}) " +
            "      THEN TRUE " +
            "      ELSE FALSE " +
            "    END " +
            "  WHEN ca.requirement_type = 'read' THEN " +
            "    COALESCE(ac.is_completed, FALSE) " +
            "  ELSE " +
            "    COALESCE(ac.is_completed, FALSE) " +
            "END " +
            "FROM class_assignments ca " +
            "LEFT JOIN assignment_completions ac ON ac.assignment_id = ca.id AND ac.book_id = #{bookId} AND ac.user_id = #{userId} " +
            "WHERE ca.id = #{assignmentId}")
    Boolean selectIsCompletedByBookIdAndAssignmentIdAndUserId(Long bookId, Long assignmentId, Long userId);

    /**
     * 根据绘本ID查询作业关联
     *
     * @param bookId 绘本ID
     * @return 作业关联列表
     */
    default List<AssignmentBookDO> selectByBookId(Long bookId) {
        return selectList(new LambdaQueryWrapperX<AssignmentBookDO>()
                .eq(AssignmentBookDO::getBookId, bookId)
                .orderByDesc(AssignmentBookDO::getCreateTime));
    }

    /**
     * 根据作业ID删除所有绘本关联
     *
     * @param assignmentId 作业ID
     * @return 影响行数
     */
    default int deleteByAssignmentId(Long assignmentId) {
        return delete(new LambdaQueryWrapperX<AssignmentBookDO>()
                .eq(AssignmentBookDO::getAssignmentId, assignmentId));
    }

    /**
     * 统计作业包含的绘本数量
     *
     * @param assignmentId 作业ID
     * @return 绘本数量
     */
    default Integer countByAssignmentId(Long assignmentId) {
        return Math.toIntExact(selectCount(new LambdaQueryWrapperX<AssignmentBookDO>()
                .eq(AssignmentBookDO::getAssignmentId, assignmentId)));
    }

}
